package com.gf.gf_data.controller;

import com.gf.gf_data.dto.BaseResult;
import com.gf.gf_data.dto.ResultMessage;
import com.gf.gf_data.entity.LoginRecord;
import com.gf.gf_data.service.AccountService;
import com.gf.gf_data.entity.Account;
import com.gf.gf_data.dto.AccessToken;
import com.gf.gf_data.service.LoginRecordService;
import com.gf.gf_data.util.JWTUtil;
import com.gf.gf_data.util.PasswordHelperUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * JWT 授权认证控制处理器
 * Created by Eternal_L on 2018/1/9.
 */
@RestController
@RequestMapping("/oauth")
public class JWTController {

    private static Logger log = LoggerFactory.getLogger(JWTController.class);

    private final AccountService accountService;

    private final LoginRecordService loginRecordService;

    @Autowired
    public JWTController(AccountService accountService, LoginRecordService loginRecordService) {
        this.accountService = accountService;
        this.loginRecordService = loginRecordService;
    }


    @GetMapping(value = "/reg", produces = MediaType.APPLICATION_JSON_VALUE)
    public BaseResult register(Account account) {
        account.setAreaCode("+" + account.getAreaCode());
        account.setPassword(PasswordHelperUtil.getEncryptPassword("123456", account.getPassword()));
        account.setSalt("123456");
        account.setStatus(0);
        account.setRole("admin");
        System.out.println("----------------->>>>" + account.getAreaCode());
        account.setRegTime(new Date(System.currentTimeMillis()));
        if (accountService.regAccount(account))
            return new BaseResult<>(true, "OK");
        return new BaseResult<>(false, 1, "Failure");
    }

    /**
     * 登录获取token
     *
     * @param phone
     * @param password
     * @return
     */
    @GetMapping(value = "/token", produces = MediaType.APPLICATION_JSON_VALUE)
    public BaseResult login(@RequestParam("areaCode") String areaCode,
                            @RequestParam("phone") String phone,
                            @RequestParam("password") String password) {
        try {
            // 验证账户
            String ac = "+" + areaCode;
            System.out.println(ac);
            Account account = accountService.findAccountByPhone(phone, ac);
            if (account == null) {
                return new BaseResult(false,
                        ResultMessage.INVALID_TOKEN.getState(), ResultMessage.INVALID_TOKEN.getMsg());
            } else {
                // 判断状态
                if (account.getStatus() != 0) {
                    return new BaseResult(false, ResultMessage.ACCOUNT_IS_NOT_AVAILABLE.getState(),
                            ResultMessage.ACCOUNT_IS_NOT_AVAILABLE.getMsg());
                }

                // 验证密码
                String md5Password = PasswordHelperUtil.getEncryptPassword(account.getSalt(), password);
                if (!md5Password.equals(account.getPassword()))
                    return new BaseResult(false, ResultMessage.WRONG_ACCOUNT_NAME_OR_PASSWORD.getState(),
                            ResultMessage.WRONG_ACCOUNT_NAME_OR_PASSWORD.getMsg());
            }

            // 创建accessToken
            String accessTokenStr = JWTUtil.createJWT(
                    ac + account.getPhone(),
                    account.getId().toString(),
                    JWTUtil.TTL_MILLIS,
                    JWTUtil.getBase64SecretKey());

            // 创建accessToken返回实体
            AccessToken accessTokenEntity = new AccessToken();
            accessTokenEntity.setAccessToken(accessTokenStr);       // 设置token字符串
            accessTokenEntity.setTokenType(JWTUtil.TOKEN_TYPE);  // 设置token类型
            accessTokenEntity.setExpires(3600);                  // 设置有效时间
            accessTokenEntity.setRole(account.getRole());        // 设置角色

            // 记录登录信息
            boolean flag = loginRecordService.recordLoginInfo(new LoginRecord(account.getId(),
                    accessTokenStr, 0, new Date(System.currentTimeMillis())));
            if (flag)
                return new BaseResult<>(true, accessTokenEntity);
            return new BaseResult(false,
                    ResultMessage.LOGIN_FAILURE.getState(), ResultMessage.LOGIN_FAILURE.getMsg());
        } catch (Exception ex) {
            ex.printStackTrace();
            return new BaseResult(false,
                    ResultMessage.LOGIN_FAILURE.getState(), ResultMessage.LOGIN_FAILURE.getMsg());
        }
    }


    @GetMapping(value = "/failure", produces = MediaType.APPLICATION_JSON_VALUE)
    public BaseResult checkTokenFailure() {
        return new BaseResult(false,
                ResultMessage.INVALID_TOKEN.getState(), ResultMessage.INVALID_TOKEN.getMsg());
    }

    @GetMapping(value = "/token/ex", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public BaseResult failure(){
        log.info("invoke-------------/oauth/token/ex.get");

        return new BaseResult<>(true, ResultMessage.TOKEN_DATA_ID_ABNORMAL.getState(),
                ResultMessage.TOKEN_DATA_ID_ABNORMAL.getMsg());
    }
}
